package org.duang.handles;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.duang.kit.ToolsKit;
/**
 * 添加允许跨域访问的域名
 *  Map<String,String>	key为代号,value为域名
 * @author laotang
 *@since 1.0
 */
public class AllowHostHandle implements IHandle {
	
	private String allowHostKey;
	private Map<String,String> accessHosts;	
	private final static String PROTOCOL = "http://";
	
	/**
	 * 允许跨域访问的域名集合
	 * @param accessHosts
	 */
	public AllowHostHandle(String allowHostKey, Map<String,String> accessHostMap){
		if(ToolsKit.isNotEmpty(allowHostKey) && ToolsKit.isNotEmpty(accessHostMap)) {
			this.allowHostKey = allowHostKey;
			this.accessHosts = new HashMap<String,String>(accessHostMap.size());
			for(Iterator<Entry<String,String>> it = accessHostMap.entrySet().iterator(); it.hasNext();){
				Entry<String,String> entry = it.next();
				String host = entry.getValue();
				if(!host.startsWith(PROTOCOL)){
					host = PROTOCOL +  host;
				}
				this.accessHosts.put(entry.getKey(), host);
			}
		}
	}

	@Override
	public void execute(String target, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if(ToolsKit.isNotEmpty(accessHosts)){
			String key = request.getParameter(this.allowHostKey);
			String serverName = accessHosts.get(key);
			if(ToolsKit.isNotEmpty(serverName)){
				response.setHeader("Access-Control-Allow-Origin", serverName);
				response.setHeader("Access-Control-Allow-Credentials", "true");
				response.setHeader("Access-Control-Allow-Headers", "accept,content-type");
			}
		}
	}

}
